package com.gxar.uaa.server.base.controller;

import com.gxar.common.entity.Result;
import com.gxar.common.entity.login.LoginUserThread;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.warning.ApiLog;
import com.gxar.uaa.api.dto.menu.SysMenu;
import com.gxar.uaa.server.base.common.constant.CommonConstant;
import com.gxar.uaa.server.base.model.menu.mapper.MenuMapStruct;
import com.gxar.uaa.server.base.model.menu.vo.request.MenuCreateRequest;
import com.gxar.uaa.server.base.model.menu.vo.request.MenuToRoleRequest;
import com.gxar.uaa.server.base.model.menu.vo.request.MenuUpdateRequest;
import com.gxar.uaa.server.base.model.menu.vo.response.MenuCreateResponse;
import com.gxar.uaa.server.base.model.menu.vo.response.MenuInfoResponse;
import com.gxar.uaa.server.base.model.menu.vo.response.MenuTreeResponse;
import com.gxar.uaa.server.base.model.menu.vo.response.MenuUpdateResponse;
import com.gxar.uaa.server.db.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/1/24 17:51
 */
@Api(tags = "菜单接口")
@RestController
@RequestMapping("/admin/api/menus")
@RequiredArgsConstructor
@Slf4j
public class MenuController {

    private final MenuService menuService;

    @Operation(summary = "删除菜单")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            menuService.removeById(id);
            return Result.success(true);
        } catch (Exception ex) {
            log.error("memu-delete-error", ex);
            return Result.error("操作失败");
        }
    }

    @Operation(summary = "根据roleId获取对应的菜单")
    @GetMapping("/{roleId}/menus")
    public Result<List<MenuInfoResponse>> findMenusByRoleId(@PathVariable Long roleId) {
        Set<Long> roleIds = new HashSet<>();
        roleIds.add(roleId);
        //获取该角色对应的菜单
        List<SysMenu> roleMenus = menuService.findByRoles(roleIds);
        List<MenuInfoResponse> menuInfoResponses = MenuMapStruct.INSTANCE.sysMenuToInfoResponseList(roleMenus);
        return Result.success(menuInfoResponses);
    }

    @ApiOperation("根据roleCodes获取对应的权限")
    @GetMapping("/{roleCodes}")
    public List<SysMenu> findMenuByRoles(@PathVariable String roleCodes) {
        List<SysMenu> result = null;
        if (StringUtils.isNotEmpty(roleCodes)) {
            Set<String> roleSet = Arrays.stream(roleCodes.split(",")).collect(Collectors.toSet());
            result = menuService.findByRoleCodes(LoginUserThread.get().getApp(), roleSet, CommonConstant.PERMISSION);
        }
        return result;
    }

    @ApiOperation("角色分配菜单")
    @PostMapping("/granted")
    public Result<Boolean> setMenuToRole(@RequestBody MenuToRoleRequest sysMenu) {
        menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds(), sysMenu.getHalfMenuIds());
        return Result.success("操作成功", true);
    }

    @ApiOperation("查询所有菜单")
    @GetMapping()
    public Result<List<MenuInfoResponse>> pageList(@RequestParam(value = "type", required = false) Integer type) {
        List<MenuInfoResponse> responses = menuService.pageList(type);
        return Result.success(responses);
    }

    @ApiOperation("获取菜单以及顶级菜单")
    @GetMapping("/findOnes")
    public Result<List<MenuInfoResponse>> findOnes() {
        List<MenuInfoResponse> responses = menuService.findOnes();
        return Result.success(responses);
    }

    @GetMapping("/current")
    @ApiOperation("查询当前用户菜单")
    public Result<List<MenuTreeResponse>> findMyMenu() {
        UserProfile user = LoginUserThread.get();
        List<MenuTreeResponse> menus = menuService.findTreeByUserId(user.getId(), null);
        return Result.success(menus);
    }

    @PostMapping("")
    @ApiOperation("创建菜单")
    @ApiLog
    public Result<MenuCreateResponse> create(@RequestBody @Valid MenuCreateRequest request) {
        UserProfile user = LoginUserThread.get();
        MenuCreateResponse response = menuService.create(user, request);
        return Result.success(response);
    }

    @PutMapping("/{id}")
    @ApiOperation("更新菜单")
    @ApiLog
    public Result<MenuUpdateResponse> update(@PathVariable Long id, @RequestBody @Valid MenuUpdateRequest request) {
        UserProfile user = LoginUserThread.get();
        MenuUpdateResponse response = menuService.update(user, id, request);
        return Result.success(response);
    }

    @GetMapping("{id}/child")
    @ApiOperation("查询当前菜单的子菜单")
    public Result<List<MenuInfoResponse>> findChildMenu(@PathVariable Long id) {
        UserProfile user = LoginUserThread.get();
        List<MenuInfoResponse> menus = menuService.findChildMenu(user.getId(), id, null);
        return Result.success(menus);
    }

}
